

import Database from "@tauri-apps/plugin-sql";
import { homePath, createDirs, uuid, getG01DataBase } from '../../utils';

export const localSharingGetSharedObject = async (objectType: string, referId: string): Promise<{ sharedObjectIdentifier: string, localVersion: string, lastVersion: string } | null> => {
    const db = await getG01DataBase();
    //
    let items: Array<any> = await db.select(`select * from sharing_shared_objects where object_type = $1 and refer_id = $2`, [objectType, referId]);
    if (items && items.length > 0) {
        return {
            sharedObjectIdentifier: items[0].shared_object_identifier,
            localVersion: items[0].local_version,
            lastVersion: items[0].last_version,
        };
    }
    return null;
}


export const localSharingSaveSharedObject = async (objectType: string, referId: string, identifier: string): Promise<number | null> => {
    const db = await getG01DataBase();
    //
    await db.execute(`insert into sharing_shared_objects(shared_object_identifier,object_type,refer_id,last_version,local_version)Values($1,$2,$3,$4,$5)`,
        [identifier, objectType, referId, '', '']);

    let res: Array<any> = await db.select('SELECT last_insert_rowid() nid');
    console.log(res);
    if (res && res.length > 0) {
        return res[0].nid;
    }
    return null;
}

export const localSharingRemoveSharedObject = async (objectType: string, referId: string, identifier: string): Promise<number> => {
    const db = await getG01DataBase();
    //
    await db.execute(`delete from sharing_shared_objects where  shared_object_identifier = $1 and  object_type = $2 and refer_id = $3 `,
        [identifier, objectType, referId]);

    return 0;
}


export const localSharingUpdateLastVersion = async (objectType: string, referId: string, identifier: string, lastVersion: string): Promise<number> => {
    const db = await getG01DataBase();
    //
    await db.execute(`update sharing_shared_objects set  last_version = $1 where  shared_object_identifier = $2 and  object_type = $3 and refer_id = $4 `,
        [lastVersion, identifier, objectType, referId]);

    return 0;
}

export default {}